package com.example.aiagent.constant;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.jsoup.Jsoup;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class AiDocumentReader {

    private final String FILE_DIR = FileConstant.FILE_SAVE_DIR + "/file";


    /**
     * 统一读取文档内容
     * @param file 文档文件
     * @return 纯文本内容
     */
    public static String readForAi(File file) throws IOException {
        String fileName = file.getName().toLowerCase();

        if (fileName.endsWith(".html") || fileName.endsWith(".htm")) {
            return readWebPage(file);
        } else if (fileName.endsWith(".docx")) {
            return readDocx(file);
        } else if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")) {
            return readExcel(file);
        } else if (fileName.endsWith(".pptx")) {
            return readPpt(file);
        } else if (fileName.endsWith(".pdf")) {
            return readPdf(file);
        } else {
            // 默认按文本文件处理
            return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        }
    }

    // 读取网页内容
    private static String readWebPage(File file) throws IOException {
        String html = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        return Jsoup.parse(html).text(); // 提取纯文本
    }

    // 读取Word文档 (.docx)
    private static String readDocx(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file);
             XWPFDocument doc = new XWPFDocument(fis)) {

            StringBuilder sb = new StringBuilder();
            for (XWPFParagraph para : doc.getParagraphs()) {
                sb.append(para.getText()).append("\n");
            }
            return sb.toString();
        }
    }

    // 读取Excel内容
    private static String readExcel(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file);
             Workbook workbook = WorkbookFactory.create(fis)) {

            StringBuilder sb = new StringBuilder();
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                // 读取每个工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                sb.append("工作表: ").append(sheet.getSheetName()).append("\n");

                // 读取每行
                for (Row row : sheet) {
                    // 读取每个单元格
                    for (Cell cell : row) {
                        sb.append(getCellValue(cell)).append("\t");
                    }
                    sb.append("\n");
                }
                sb.append("\n");
            }
            return sb.toString();
        }
    }

    // 获取单元格的值
    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    // 读取PPT内容
    private static String readPpt(File file) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (InputStream is = new FileInputStream(file);
             XMLSlideShow ppt = new XMLSlideShow(is)) {

            for (XSLFSlide slide : ppt.getSlides()) {
                for (XSLFShape shape : slide.getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        // 明确转换为XSLFTextShape才能调用getText()方法
                        XSLFTextShape textShape = (XSLFTextShape) shape;
                        sb.append(textShape.getText()).append("\n");
                    }
                }
            }
        }
        return sb.toString();
    }

    // 读取PDF内容 - 使用PDFBox的Loader类来加载文档
    private static String readPdf(File file) throws IOException {
        // 对于PDFBox 2.0及以上版本，使用Loader类加载文档
        try (PDDocument document = Loader.loadPDF(file)) {
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(document);
        }
    }

    // 按照文件路径打开文件
    public String readFile(String fileName) throws IOException {
        String filePath = FILE_DIR + "/" + fileName;
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不存在: " + filePath);
            return null;
        }
        // 读取文件内容
        return readForAi(file);
    }
}
